/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package towerz.states;

import java.io.IOException;
import java.util.Vector;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import towerz.component.Button;
import towerz.component.ButtonPush;
import towerz.system.BitmapFont;
import towerz.system.StateManager;
import towerz.system.StringManager;
import towerz.system.Utilities;
import towerz.system.xml.XmlNode;
import towerz.system.xml.XmlReaderWriter;

/**
 *
 * @author TimotiusNC
 */
public class StateLevel extends GameState {
	public StateLevel() {
		this(0);
	}

	public StateLevel(int selected){
		super(GameState.LEVELS, StateManager.instance().getBackgroundImage());

		//Initialize
		m_Selected 	= selected;
		m_Entering	= true;
		m_Exiting	= false;
		m_AnimationTime = 1;
		initLevels();
		
		//Create image
		try {
			m_PanelImage	= Image.createImage(Utilities.INTERFACE_FOLDER + "/level-panel.png");
			m_ReturnImage	= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(StringManager.instance().getString("return"), 0x00000000);
		} catch (IOException ex) {}
		
		m_MapY		= - m_IndonesiaImg.getHeight();
		m_PanelX	= - m_PanelImage.getWidth();
	}

	private void initLevels(){
		//Create buttons
		m_Buttons = new Vector();
                
		//Create Indonesia's image
		try {
			m_IndonesiaImg = Image.createImage(Utilities.INTERFACE_FOLDER + "/indonesia.png");
		} catch (IOException ex) {}

		//Get max level
		m_MaxLevel = Utilities.getInt(Utilities.MAX_LEVEL_RMS, 1);

		initLevelInfos(Utilities.LEVELINFO_FILE, m_MaxLevel);
	}

	public void initLevelInfos(String levelPath, int maxLevel){
		m_LevelInfos = new Vector();

		//Read XML
		XmlNode xmlNode = XmlReaderWriter.getInstance().readFromXmlFile(levelPath);

		for(int i=0; i < maxLevel; ++i){
			//Get child
			XmlNode Child = (XmlNode)xmlNode.getChildren().elementAt(i);
			ButtonPush NewButton = new ButtonPush(StringManager.instance().getString("chapter") + " " + Child.getAttribute("index"), i, 50,  4 + (i*28));

			//Add
			m_Buttons.addElement(NewButton);
			m_LevelInfos.addElement(new LevelInfo(Child));
		}
	}

	public void keyPressed(int key){
		//Super
		super.keyPressed(key);

		if (key == -7 || key == 35) { //Is right pressed?
			//Cancel sound
			StateManager.instance().playSFX("/cancel.wav");

			m_Exiting = true;
		}
	}

	public void update(long time, int keys) {
		//Super
		super.update(time, keys);
		
		if (m_Entering) {
			//Skip if first time
			if (m_AnimationTime == 1) m_AnimationTime = 2;
			else {			
				//Increase
				m_AnimationTime += time;

				//Set
				float Comparison	= (float)m_AnimationTime / (float)ANIMATE_TIME;
				m_MapY				= - m_IndonesiaImg.getHeight() + (int)((m_IndonesiaImg.getHeight() + 10) * Comparison);
				m_PanelX			= - m_PanelImage.getWidth() + (int)(m_PanelImage.getWidth() * Comparison);

				//Check time and fire
				if (m_AnimationTime > ANIMATE_TIME || keys != 0) {
					m_Entering		= false;
					m_AnimationTime = 0;

					//Finalize button
					m_MapY		= 10;
					m_PanelX	= 0;
				}
			}
		} else if (m_Exiting) {
			//If
			if (m_AnimationTime < 0) {
				//No longer exiting
				m_Exiting = false;
				
				//Inactive
				m_Active = false;
			} else {			
				//Increase
				m_AnimationTime += time;

				//Set
				float Comparison	= (float)m_AnimationTime / (float)ANIMATE_TIME;
				m_MapY				= 10 - (int)((m_IndonesiaImg.getHeight() + 10) * Comparison);
				m_PanelX			= - (int)(m_PanelImage.getWidth() * Comparison);

				//Check time
				if (m_AnimationTime > ANIMATE_TIME || keys != 0) m_AnimationTime = -1;
			}
		} else {
			//Change selection based on key
			if ((keys & GameCanvas.UP_PRESSED) != 0)	m_Selected--;
			if ((keys & GameCanvas.DOWN_PRESSED) != 0)	m_Selected++;
			if ((keys & GameCanvas.DOWN_PRESSED) != 0 || (keys & GameCanvas.UP_PRESSED) != 0) {
				if (m_Buttons.size() > 1) {
					//Cursor sound
					StateManager.instance().playSFX("/cursor.wav");
				}
			}

			//Correct selection
			if (m_Selected < 0) m_Selected = m_Buttons.size() - 1;
			m_Selected = m_Selected % m_Buttons.size();

			//If button is pressed
			if ((keys & GameCanvas.FIRE_PRESSED) != 0) { 
				//Goto GAME state
				((Button)m_Buttons.elementAt(m_Selected)).setState(Button.STATE_PRESSED);

				//Based on the currently selected
				Vector param = new Vector(1);
				param.addElement(new Integer(m_Selected + 1));

				//Destroy images
				m_Buttons		= null;
				m_LevelInfos	= null;

				StateManager.instance().goTo(GameState.LOADING, param, true);
			}

			if (m_Buttons == null) return;

			//Restart state
			for (int i = 0; i < m_Buttons.size(); i++) {
				((Button)m_Buttons.elementAt(i)).setState(Button.STATE_NONE);
			}

			//Manage the selected button state
			((Button)m_Buttons.elementAt(m_Selected)).setState(Button.STATE_SELECTED);
		}
	}

	public void draw(Graphics g) {
		//Skip if no button
		if (m_Buttons == null) return;

		//Super
		super.draw(g);
		
		//Draws images
		g.drawImage(StateManager.instance().getDarkImage(), 0, 0, Graphics.LEFT | Graphics.TOP);
		g.drawImage(m_IndonesiaImg, m_Background.getWidth() - (m_IndonesiaImg.getWidth() + 10), m_MapY, Graphics.TOP | Graphics.LEFT);
		g.drawImage(m_PanelImage, m_PanelX, 0, Graphics.LEFT | Graphics.TOP);
		
		//Draw buttons
		for (int i = 0; i < m_Buttons.size(); ++i) {
			((Button)m_Buttons.elementAt(i)).setX(m_PanelX + 5);
			((Button)m_Buttons.elementAt(i)).draw(g);
		}
		
		//If not entering or exiting
		if (m_AnimationTime == 0) {
			//Draw Level
			drawLevel(g, (LevelInfo)m_LevelInfos.elementAt(m_Selected));
			g.drawImage(m_ReturnImage, StateManager.instance().getWidth() - 4, StateManager.instance().getHeight()-4, Graphics.RIGHT | Graphics.BOTTOM);
		}
	}

	public void drawLevel(Graphics g, LevelInfo level) {
		//Draw X
		g.setColor(0xFFFF0404);
		g.drawString("x", level.getCrossX(), level.getCrossY(), Graphics.TOP | Graphics.LEFT);

		//Draw Level Name and Year
		g.drawImage(level.getName(), m_Background.getWidth() - 202, m_IndonesiaImg.getHeight() + 15, Graphics.TOP | Graphics.LEFT);
		g.drawImage(level.getYear(), m_Background.getWidth() - 10, m_IndonesiaImg.getHeight() + 15, Graphics.TOP | Graphics.RIGHT);

		//Draw Description
		for(int i=0; i < level.getDescriptions().length; ++i)
			g.drawImage(level.getDescriptions()[i], m_Background.getWidth() - (202), m_IndonesiaImg.getHeight() + (40 + i*12), Graphics.TOP | Graphics.LEFT);
	}
	
	protected final long ANIMATE_TIME = 500;

	//DATA
	protected int		m_Selected;
	protected int		m_MaxLevel;
	protected Vector	m_Buttons;

	//Animation
	protected int		m_MapY;
	protected int		m_PanelX;
	protected boolean	m_Entering;
	protected boolean	m_Exiting;
	protected int		m_AnimationTime;

	protected Image     m_IndonesiaImg;
	protected Image		m_ReturnImage;
	protected Image		m_PanelImage;
	protected Vector	m_LevelInfos;

	protected class LevelInfo {
		protected LevelInfo() {}

		public LevelInfo(XmlNode xmlNode){
			//Initialize variable
			String Name			= "";
			String Year			= "";
			Vector Descriptions = new Vector();

			//For each child
			for(int i=0; i < xmlNode.getChildren().size(); i++) {
				//Get node
				String Tag 		= ((XmlNode)xmlNode.getChildren().elementAt(i)).getNodeName();
				String Value 	= ((XmlNode)((XmlNode)xmlNode.getChildren().elementAt(i)).getChildren().elementAt(0)).getNodeValue();

				if (Tag.equals("year"))	Year = Value;
				else if (Tag.equals("position")) {
					String[] xPos = Utilities.split(Value, ",");
					m_CrossX = Integer.parseInt(xPos[0]);
					m_CrossY = Integer.parseInt(xPos[1]);
				}
				if (Tag.equals("names")) {
					//Get child
					XmlNode Child = (XmlNode)xmlNode.getChildren().elementAt(i);
					
					//For each child
					for (int j = 0; j < Child.getChildren().size(); j++) {
						//If name
						if (((XmlNode)Child.getChildren().elementAt(j)).getNodeName().equals("name"))
							if (((XmlNode)Child.getChildren().elementAt(j)).getAttribute("language").equals(StringManager.instance().getTag()))
								Name = ((XmlNode)((XmlNode)Child.getChildren().elementAt(j)).getChildren().elementAt(0)).getNodeValue();
					}
				}
				else if (Tag.equals("descriptions")) {					
					//For each child
					for (int j = 0; j < ((XmlNode)xmlNode.getChildren().elementAt(i)).getChildren().size(); j++) {
						//Get grandchild
						XmlNode GrandChild = (XmlNode)((XmlNode)xmlNode.getChildren().elementAt(i)).getChildren().elementAt(j);
						
						//If description
						if (GrandChild.getNodeName().equals("description")) {
							if (GrandChild.getAttribute("language").equals(StringManager.instance().getTag())) {								
								for (int k = 0; k <  GrandChild.getChildren().size(); k++) {
									Value = ((XmlNode)((XmlNode)GrandChild.getChildren().elementAt(k)).getChildren().elementAt(0)).getNodeValue();
									Descriptions.addElement(Value);
								}
							}
						}
					}
				}
			}
			
			//Create images
			m_NameString			= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(Name.toUpperCase(), 0x00000000);
			m_YearString			= BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText(Year + " " + StringManager.instance().getString("ad"), 0x00000000);
			m_DescriptionStrings	= new Image[Descriptions.size()];
			for (int i = 0; i < m_DescriptionStrings.length; i++)
				m_DescriptionStrings[i] = BitmapFont.getFont(BitmapFont.MAIN).renderTransparentText((String)Descriptions.elementAt(i), 0x000000);
		}
		
		public int getCrossX()				{	return m_CrossX;				}
		public int getCrossY()				{	return m_CrossY;				}
		public Image getName()				{	return m_NameString;			}
		public Image getYear()				{	return m_YearString;			}
		public Image[] getDescriptions()	{	return m_DescriptionStrings;	}

		//DATA
		protected int m_CrossX;
		protected int m_CrossY;
		
		//Image
		protected Image		m_NameString;
		protected Image		m_YearString;
		protected Image[]	m_DescriptionStrings;
	}
}
